package gui;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.SwingWorker;

import tools.OptionReader;
import tools.OptionWriter;

/**
 * Klasse stellt Login bereit
 * 
 * @author Michi
 * 
 */
public class LogInPanel extends JFrame {

	/**
	 * 
	 */
	private static final long serialVersionUID = 8600104347174129792L;
	private JTextField textnutzer;
	private JPasswordField textpasswort;
	private JPasswordField textpasswortbestaetigen;
	private JTextField textemail;
	private Connection connection = null;
	private JButton btnNew;
	private JLabel lblPWBestaetigen;
	private JButton btnStart;
	private JLabel lblEmail;
	private JButton btnStart_2;
	private JLabel lblEmailpw;
	private JPasswordField textemailpw;
	private int idUser;
	private int idAccount;
	private int idBooks;
	private int idEntrys;
	private int idAdress;
	private int idCalendar;
	
	private int speak = 0;
	private OptionReader or;
	
	private String[] benutzer = {"Benutzer:", "User:", "Usor:"};
	private String[] pw = {"Passwort:", "Password:", "Secretum Verbum:"};
	private String[] neuAnmelden = {"Neu Anmelden", "New Account", "Registri Nunc"};
	private String[] pwB = {"Passwort Bestätigen:", "Confirm Password:", "Confirmare:"};
	private String[] Email = {"E-Mail:", "Email:", "Litterus Technicus:"};
	private String[] emailPW = {"E-Mail Passwort:", "Email Password:", "Litterus T. S.V.:"};

	private JLabel wronginputwarning;

	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					LogInPanel frame = new LogInPanel();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Stellt Verbindung zur DB her
	 * 
	 * @return
	 */
	public boolean connect() {

		try {
			Class.forName("com.mysql.jdbc.Driver");
			connection = DriverManager
					.getConnection("jdbc:mysql://win9142.informatik.uni-wuerzburg.de:3306?user=awesomefireballs&password=jesus");

		} catch (ClassNotFoundException e) {

			e.printStackTrace();
		} catch (SQLException e) {

			e.printStackTrace();
			return false;
		}

		return true;
	}

	/**
	 * Liest User aus Datenbank aus
	 * 
	 * @return ResultSet mit Usern
	 * @throws SQLException
	 */
	public ResultSet getUsersfromDb() throws SQLException {

		Statement stat = connection.createStatement();

		stat.executeQuery("use `sopra-ws12-awesome_fireballs`;");

		ResultSet rs = stat.executeQuery("SELECT User.* FROM User;");

		return rs;

	}

	/**
	 * Konstruktor
	 */
	public LogInPanel() {
		
		// OptionRead Test
		or = new OptionReader();
		try {
			or.getOpionsFromFile();
		} catch (IOException e2) {

			e2.printStackTrace();
		}

		speak = Integer.parseInt(or.getLanguage());
		
		

		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		Dimension size = new Dimension(700, 300);
		setSize(size);
		setPreferredSize(size);
		setMinimumSize(size);
		setMaximumSize(size);
		getContentPane().setLayout(null);

		JLabel lblLogin = new JLabel("Login");
		lblLogin.setFont(new Font("Lucida Grande", Font.BOLD, 32));
		lblLogin.setBounds(36, 20, 200, 57);
		getContentPane().add(lblLogin);

		JLabel lblUsername = new JLabel(benutzer[speak]);
		lblUsername.setHorizontalAlignment(SwingConstants.RIGHT);
		lblUsername.setBounds(36, 102, 136, 16);
		getContentPane().add(lblUsername);

		JLabel lblPasswort = new JLabel(pw[speak]);
		lblPasswort.setHorizontalAlignment(SwingConstants.RIGHT);
		lblPasswort.setBounds(36, 147, 136, 16);
		getContentPane().add(lblPasswort);

		lblPWBestaetigen = new JLabel(pwB[speak]);
		lblPWBestaetigen.setBounds(36, 192, 136, 16);
		lblPWBestaetigen.setHorizontalAlignment(SwingConstants.RIGHT);
		lblPWBestaetigen.setVisible(false);
		getContentPane().add(lblPWBestaetigen);

		lblEmail = new JLabel(Email[speak]);
		lblEmail.setHorizontalAlignment(SwingConstants.RIGHT);
		lblEmail.setBounds(36, 237, 136, 16);
		lblEmail.setVisible(false);
		getContentPane().add(lblEmail);
		
		lblEmailpw = new JLabel(emailPW[speak]);
		lblEmailpw.setHorizontalAlignment(SwingConstants.RIGHT);
		lblEmailpw.setBounds(36, 276, 136, 16);
		lblEmailpw.setVisible(false);
		getContentPane().add(lblEmailpw);

		textnutzer = new JTextField();
		textnutzer.setBounds(195, 96, 274, 28);
		getContentPane().add(textnutzer);
		textnutzer.setColumns(10);

		textpasswort = new JPasswordField();
		textpasswort.setColumns(10);
		textpasswort.setBounds(195, 141, 274, 28);
		getContentPane().add(textpasswort);

		textpasswortbestaetigen = new JPasswordField();
		textpasswortbestaetigen.setColumns(10);
		textpasswortbestaetigen.setBounds(195, 186, 274, 28);
		textpasswortbestaetigen.setVisible(false);
		getContentPane().add(textpasswortbestaetigen);

		textemail = new JTextField();
		textemail.setColumns(10);
		textemail.setBounds(195, 231, 274, 28);
		textemail.setVisible(false);
		getContentPane().add(textemail);
		
		textemailpw = new JPasswordField();
		textemailpw.setColumns(10);
		textemailpw.setBounds(195, 276, 274, 28);
		textemailpw.setVisible(false);
		getContentPane().add(textemailpw);

		btnStart = new JButton("Login");
		btnStart.setBounds(482, 142, 80, 29);
		getContentPane().add(btnStart);

		ActionListener einloggen = new ActionListener() {

			@SuppressWarnings("deprecation")
			@Override
			public void actionPerformed(ActionEvent arg0) {
				wronginputwarning.setVisible(false);
				forceRepaint();

				if (textnutzer.getText().isEmpty()
						|| textpasswort.getText().isEmpty()) {
					wronginputwarning.setVisible(true);

				} else {
					// Holt username und passwort aus den Textfeldern
					String nutzer = textnutzer.getText();
					String passwort = textpasswort.getText();

					connect();
					ResultSet allusers = null;

					try {
						// Holt resultset mit allen Nutzern aus DB
						allusers = getUsersfromDb();

						while (allusers.next()) {

							// Vergleicht Nutzer in RS mit Nutzer aus Textfeld
							// bis richtiger Nutzer gefunden
							if (allusers.getString("name").equals(nutzer)) {

								// Checkt ob eingegebens passwort korrekt ist
								// bzw mit dem des Nutzers in DB uebereinstimmt
								if (allusers.getString("password").equals(
										passwort)) {
									wronginputwarning.setVisible(false);

									int id = allusers.getInt("idUser");
									Test.iduser = id;
									String options = "";
									Statement stat = connection
											.createStatement();
									ResultSet rs = stat
											.executeQuery("SELECT * FROM Account WHERE idUser="
													+ Test.iduser + " ;");

									while (rs.next()) {
										options += "*FireBallOptionsFile*"
												+ "\n";
										options += rs.getString("viewtype")
												+ "\n";
										options += "calOpt2" + "\n";
										options += "calOpt3" + "\n";
										options += rs.getString("sort") + "\n";
										options += rs.getString("conview")
												+ "\n";
										options += "conOpt3" + "\n";
										options += rs.getString("sorttodo")
												+ "\n";
										options += rs.getString("todoview")
												+ "\n";
										options += "toDoOpt3" + "\n";
										options += rs.getString("email") + ","
												+ rs.getString("imap_server")
												+ ","
												+ rs.getString("pop3_server")
												+ ","
												+ rs.getString("smtp_server")
												+ ","
												+ rs.getString("imap_port")
												+ ","
												+ rs.getString("pop3_port")
												+ ","
												+ rs.getString("provider")
												+ ","
												+ rs.getString("mail_pass")
												+ ","
												+ rs.getString("smtp_port")
												+ "\n";
										options += "mailOpt2" + "\n";
										options += "mailOpt3" + "\n";
										options += rs.getString("language")
												+ "\n";
										options += rs.getString("rcolor") + ","
												+ rs.getString("gcolor") + ","
												+ rs.getString("bcolor") + "\n";
										options += rs.getString("timeformat");

									}

									@SuppressWarnings("unused")
									OptionWriter ow = new OptionWriter(options);

									Test startprog = new Test();

									startprog.setVisible(true);
									System.out.println(id);
									dispose();

								} else {
									// Open Dialog wrong password
									System.out.println("WRONG PASSWORD!!!");
									wronginputwarning.setVisible(true);
								}

							}
						}
						wronginputwarning.setVisible(true);
					} catch (SQLException e) {

						e.printStackTrace();
					}

				}

			}
		};

		btnStart.addActionListener(einloggen);

		btnNew = new JButton(neuAnmelden[speak]);
		btnNew.setBounds(352, 42, 117, 29);
		getContentPane().add(btnNew);

		ActionListener makeNewUser = new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {

				Dimension size = new Dimension(700, 400);
				setSize(size);
				setPreferredSize(size);
				setMinimumSize(size);
				setMaximumSize(size);
				btnNew.setVisible(false);
				btnStart.setVisible(false);
				lblPWBestaetigen.setVisible(true);
				textpasswortbestaetigen.setVisible(true);
				lblEmail.setVisible(true);
				textemail.setVisible(true);
				btnStart_2.setVisible(true);
				textemailpw.setVisible(true);
				lblEmailpw.setVisible(true);

				// forceRepaint();

			}
		};

		btnNew.addActionListener(makeNewUser);

		btnStart_2 = new JButton("Login");
		btnStart_2.setBounds(482, 276, 80, 29);
		btnStart_2.setVisible(false);
		getContentPane().add(btnStart_2);

		ActionListener newUserToDB = new ActionListener() {

			@SuppressWarnings("deprecation")
			@Override
			public void actionPerformed(ActionEvent e) {

				String user = textnutzer.getText();
				String pw = textpasswort.getText();
				String pwTest = textpasswortbestaetigen.getText();
				String email = textemail.getText();
				String emailpw = textemailpw.getText();
				Boolean test = true;

				if (user.isEmpty() || pw.isEmpty() || pwTest.isEmpty()
						|| email.isEmpty() || emailpw.isEmpty()) {
					// FALLS EINGABEWERTE FEHLEN FEHLERMELDUNG!!
					JOptionPane.showMessageDialog(null,
							"Es fehlt eine Eingabe!", "Fehlende Eingabe",
							JOptionPane.ERROR_MESSAGE);

				} else if (!pw.equals(pwTest)) {
					// FALLS PW NICHT MIT BESTAETIGUNGSEINGABE UEBEREINSTIMMT!
					JOptionPane.showMessageDialog(null,
							"Passwort stimmt nicht mit Bestätigung überein!",
							"Haaalt! Stop!", JOptionPane.ERROR_MESSAGE);

				} else {

					connect();

					ResultSet allusers = null;
					String pattern = "[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})";
					Pattern mailpattern = Pattern.compile(pattern);
					String testmail = textemail.getText();
					Matcher mailmatcher = mailpattern.matcher(testmail);

					try {
						allusers = getUsersfromDb();

						while (allusers.next()) {
							if (allusers.getString("name").equals(user)) {

								// DOPPELTE NUTZER FEHLERMELDUNG!
								JOptionPane.showMessageDialog(null,
										"Nutzer existiert bereits!",
										"Haaalt! Stop!",
										JOptionPane.ERROR_MESSAGE);
								test = false;
							}
						}

						if (!mailmatcher.matches()) {
							JOptionPane.showMessageDialog(null,
									"Keine gültige E-mail-Adresse",
									"Haaalt! Stop!", JOptionPane.ERROR_MESSAGE);
							test = false;
						}

						if (test) {

							idUser = 0;
							idAccount = 1;
							idBooks = 0;
							idEntrys = 0;
							idAdress = 0;
							idCalendar = 0;

							@SuppressWarnings("rawtypes")
							SwingWorker worker = new SwingWorker() {

								protected Object doInBackground() {

									// GET CONNECTION
									try {
										Class.forName("com.mysql.jdbc.Driver");
										connection = DriverManager
												.getConnection("jdbc:mysql://win9142.informatik.uni-wuerzburg.de:3306?user=awesomefireballs&password=jesus");
									} catch (ClassNotFoundException e) {
										e.printStackTrace();
									} catch (SQLException e) {
										e.printStackTrace();
									}

									Statement stat = null;

									try {
										stat = connection.createStatement();
										stat.executeQuery("use `sopra-ws12-awesome_fireballs`;");

										// GET NEW USER ID
										ResultSet rs = stat
												.executeQuery("SELECT idUser FROM `sopra-ws12-awesome_fireballs`.`User`ORDER BY idUser DESC LIMIT 1;");
										while (rs.next()) {
											idUser = rs.getInt(1) + 1;
										}

										// GET NEW ACCOUNT ID
										ResultSet rs2 = stat
												.executeQuery("SELECT idAccount FROM `sopra-ws12-awesome_fireballs`.`Account` Order BY idAccount DESC LIMIT 1;");
										while (rs2.next()) {
											idAccount = idAccount
													+ rs2.getInt(1);
										}

										// GET NEW BOOK ID
										ResultSet rs3 = stat
												.executeQuery("SELECT idBooks FROM `sopra-ws12-awesome_fireballs`.`Books` Order BY idBooks DESC LIMIT 1;");
										while (rs3.next()) {
											idBooks = rs3.getInt(1) + 1;
										}

										// GET NEW ADRESS ID
										ResultSet rs4 = stat
												.executeQuery("SELECT idAdress FROM `sopra-ws12-awesome_fireballs`.`Adress`ORDER BY idAdress DESC LIMIT 1;");
										while (rs4.next()) {
											idAdress = rs4.getInt(1) + 1;
										}

										// GET NEW ENTRY ID
										ResultSet rs5 = stat
												.executeQuery("SELECT idEntrys FROM `sopra-ws12-awesome_fireballs`.`Entrys`ORDER BY idEntrys DESC LIMIT 1;;");
										while (rs5.next()) {
											idEntrys = rs5.getInt(1) + 1;
										}

										// GET NEW CALENDAR ID
										ResultSet rs6 = stat
												.executeQuery("SELECT idCalendar FROM `sopra-ws12-awesome_fireballs`.`Calendar`ORDER BY idCalendar DESC LIMIT 1;;");
										while (rs6.next()) {
											idCalendar = rs6.getInt(1) + 1;
										}

										// NAME UND PASSWORT IN USER DB
										connection.setAutoCommit(false);
										PreparedStatement pstmt = connection
												.prepareStatement("INSERT INTO User VALUES(?, ?, ?)");
										pstmt.setInt(1, idUser);
										pstmt.setString(2, textnutzer.getText());
										pstmt.setString(3,
												textpasswort.getText());

										// // UND EMAIL IN ACCOUNT DB
										Scanner scan = new Scanner(textemail.getText());
										scan.useDelimiter("@");
										scan.next();
										String domain = scan.next();
										scan.close();
										String provider = "imap";
										if(domain.equals("gmail.com")){
											provider = "imaps";
										}
										
										PreparedStatement pstmt2 = connection
												.prepareStatement("INSERT INTO Account (`idAccount`, `idUser`, `email`, `imap_server`, `smtp_server`, `pop3_server`, `mail_pass`, `provider`) VALUES(?,?,?,'imap."+domain+"','smtp."+domain+"','pop3."+domain+"',? ,'"+provider+"')");
										pstmt2.setInt(1, idAccount);
										pstmt2.setInt(2, idUser);
										pstmt2.setString(3, textemail.getText());
										pstmt2.setString(4, textemailpw.getText());
												
										// STANDARD ADRESSBUCH FUER NEUEN NUTZER
										// ERSTELLEN!
										String name = textnutzer.getText();

										PreparedStatement pstmt3 = connection
												.prepareStatement("INSERT INTO Books VALUES(?,?,?,?)");
										pstmt3.setInt(1, idBooks);
										pstmt3.setInt(2, idUser);
										pstmt3.setString(3, "Adressbuch von: "
												+ name);
										pstmt3.setInt(4, idUser);

										// NEUEN NUTZER IN EIGENES ADRESSBUCH
										// HINZUFUEGEN
										PreparedStatement pstmt4 = connection
												.prepareStatement("INSERT INTO Adress (`idAdress`, `fname`, `lname` , `email`) VALUES(?,?,?,?)");
										pstmt4.setInt(1, idAdress);
										pstmt4.setString(2, name);
										pstmt4.setString(3, " ");
										pstmt4.setString(4, textemail.getText());

										// ENTRY FUER NEUEN NUTZER FUELLEN
										PreparedStatement pstmt5 = connection
												.prepareStatement("INSERT INTO Entrys VALUES( ?, ?, ?)");
										pstmt5.setInt(1, idEntrys);
										pstmt5.setInt(2, idAdress);
										pstmt5.setInt(3, idBooks);

										// NEUEN CALENDAR FUER NUTZER ERSTELLEN
										PreparedStatement pstmt6 = connection
												.prepareStatement("INSERT INTO Calendar VALUES( ?, ?, ?, ?, ?)");
										pstmt6.setInt(1, idCalendar);
										pstmt6.setInt(2, idUser);
										pstmt6.setString(3, "Termine von: "
												+ name);
										pstmt6.setInt(4, idUser);
										pstmt6.setInt(5, 1);

										pstmt.addBatch();
										pstmt2.addBatch();
										pstmt3.addBatch();
										pstmt4.addBatch();
										pstmt5.addBatch();
										pstmt6.addBatch();

										pstmt.executeBatch();
										pstmt2.executeBatch();
										pstmt3.executeBatch();
										pstmt4.executeBatch();
										pstmt5.executeBatch();
										pstmt6.executeBatch();
										connection.commit();
										connection.setAutoCommit(true);

									} catch (SQLException e) {
										e.printStackTrace();
									}

									return null;
								}

								public void done() {

									// Thread.sleep(0);

									if (idUser != 0) {
										Test.iduser = idUser;
									}
									String options = "";
									try {
										Statement stat = connection.createStatement();
										ResultSet rs = stat
												.executeQuery("SELECT * FROM Account WHERE idUser="
														+ Test.iduser + " ;");

										while (rs.next()) {
											options += "*FireBallOptionsFile*"
													+ "\n";
											options += rs.getString("viewtype")
													+ "\n";
											options += "calOpt2" + "\n";
											options += "calOpt3" + "\n";
											options += rs.getString("sort") + "\n";
											options += rs.getString("conview")
													+ "\n";
											options += "conOpt3" + "\n";
											options += rs.getString("sorttodo")
													+ "\n";
											options += rs.getString("todoview")
													+ "\n";
											options += "toDoOpt3" + "\n";
											options += rs.getString("email") + ","
													+ rs.getString("imap_server")
													+ ","
													+ rs.getString("pop3_server")
													+ ","
													+ rs.getString("smtp_server")
													+ ","
													+ rs.getString("imap_port")
													+ ","
													+ rs.getString("pop3_port")
													+ ","
													+ rs.getString("provider")
													+ ","
													+ rs.getString("mail_pass")
													+ ","
													+ rs.getString("smtp_port")
													+ "\n";
											options += "mailOpt2" + "\n";
											options += "mailOpt3" + "\n";
											options += rs.getString("language")
													+ "\n";
											options += rs.getString("rcolor") + ","
													+ rs.getString("gcolor") + ","
													+ rs.getString("bcolor") + "\n";
											options += rs.getString("timeformat");

										}
									} catch (SQLException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}
									

									@SuppressWarnings("unused")
									OptionWriter ow = new OptionWriter(options);

									Test startprog = new Test();

									startprog.setVisible(true);

									dispose();
								}

							};

							worker.execute();

						}
					} catch (SQLException e1) {
						e1.printStackTrace();
					}

				}

			}
		};

		btnStart_2.addActionListener(newUserToDB);

		wronginputwarning = new JLabel(
				"Falsche oder keine Eingabe vorhanden, bitte erneut versuchen.");
		wronginputwarning.setForeground(Color.RED);
		wronginputwarning.setBounds(36, 196, 422, 28);
		wronginputwarning.setVisible(false);
		getContentPane().add(wronginputwarning);

	}

	public void forceRepaint() {
		paint(getGraphics());
	}
}
